package com.hyperfix.washer.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hyperfix.models.washer.dtos.RiskRecordDTO;
import com.hyperfix.models.washer.pojos.RiskRecord;
import com.hyperfix.models.washer.vos.RiskRecordQueryVO;
import com.hyperfix.washer.mapper.RiskRecordMapper;
import com.hyperfix.washer.service.RiskRecordService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.WeekFields;

/**
 * @author JiangChunYu
 * 2024/4/25
 */
@Service
public class RiskRecordServiceImpl extends ServiceImpl<RiskRecordMapper, RiskRecord> implements RiskRecordService {
    @Resource
    private RiskRecordMapper riskRecordMapper;

    @Async
    @Override
    public void asyncSave(RiskRecord riskRecord) {
        riskRecordMapper.insert(riskRecord);
    }

    @Override
    public IPage<RiskRecordDTO> list(Integer pageNum, Integer size, RiskRecordQueryVO riskRecordQueryVO) {
        IPage<RiskRecordDTO> riskRecordDTOIPage = new Page<>(pageNum, size);
        riskRecordDTOIPage = riskRecordMapper.listRiskRecordDTO(riskRecordDTOIPage, riskRecordQueryVO);
        return riskRecordDTOIPage;
    }

    @Override
    public Integer statisticDay() {
        LocalDate now = LocalDate.now();
        LocalDateTime startOfToday = LocalDateTime.of(now, LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(now, LocalTime.MAX);
        return riskRecordMapper.count(startOfToday, endOfToday);
    }

    @Override
    public Integer statisticWeek() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfWeek = now.with(WeekFields.of(DayOfWeek.MONDAY, 7).dayOfWeek(), 1).with(LocalTime.MIN);
        LocalDateTime endOfWeek = now.with(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek(), 7).with(LocalTime.MAX);
        return riskRecordMapper.count(startOfWeek, endOfWeek);
    }

    @Override
    public Integer statisticDay(Integer teamId) {
        LocalDate now = LocalDate.now();
        LocalDateTime startOfToday = LocalDateTime.of(now, LocalTime.MIN);
        LocalDateTime endOfToday = LocalDateTime.of(now, LocalTime.MAX);
        return riskRecordMapper.countByTeamId(teamId, startOfToday, endOfToday);
    }

    @Override
    public Integer statisticWeek(Integer teamId) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startOfWeek = now.with(WeekFields.of(DayOfWeek.MONDAY, 7).dayOfWeek(), 1).with(LocalTime.MIN);
        LocalDateTime endOfWeek = now.with(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek(), 7).with(LocalTime.MAX);
        return riskRecordMapper.countByTeamId(teamId, startOfWeek, endOfWeek);
    }
}
